<?php

/*
class Router, container routing requests to other components based on
URL parameter value
Copyright (C) 2012  Petr Čermák

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

require_once 'View.php';
require_once 'Checker.php';
require_once 'AbstractRouter.php';

class Router extends AbstractRouter{

    protected $pageParam = "p";

    protected function getActivePage(){
        if(isset($_GET[$this->pageParam]))
            return $_GET[$this->pageParam];
        return $this->defaultPage;
    }

    public function getPageParameter(){return $this->pageParam;}

    public function setPageParameter($pageParam){
        Checker::checkString($pageParam);
        $this->pageParam = $pageParam;
    }

    public function createPageAddress($page, $param = array()){
        $this->checkPage($page);
        if($this->getOwner() == null)$address = $this->createTopPageAddress($page);
        else{
            $owner = $this;
            do{$owner = $owner->getOwner();}
            while(!($owner == null || $owner instanceof Router));
            if($owner == null)$address = $this->createTopPageAddress($page);
            else $address = $owner->createPageAddress($this->getName()).
                            "&amp;$this->pageParam=$page";
        }
        foreach($param as $name => $value)
            if($value != null)$address .= "&amp;$name=$value";
        return $address;
    }

    private function createTopPageAddress($page){
        $address = $_SERVER['PHP_SELF']."?$this->pageParam=$page";
        $delParam = $this->getDeletableParameters();
        $urlParam = Application::getValidUrlParameters();
        foreach($urlParam as $name => $value)
            if(!in_array($name, $delParam) && $name != $this->pageParam)
                $address .= "&amp;$name=$value";
        return $address;
    }

    public function getUsedParameters(){
        $param = parent::getUsedParameters();
        $param[] = $this->pageParam;
        return $param;
    }

    // --- error checking

    private function checkPage($page){
        if(Checker::isEnabled() && (!is_string($page) || trim($page) == "" || !$this->hasComponent($page)))
            throw new InvalidArgumentException("invalid page name", null, null);
    }
    
}
?>
